<template>
  <div class="adminRole">
    <el-form ref="formRef" :inline="true" :model="form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]">
      <el-form-item label="区域名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入区域名称" clearable class="!w-[200px]" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" :loading="loading" @click="onSearch">
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="center_bg">
      <PureTableBar title="区域设置管理" :columns="columns" @refresh="onSearch" style="width: 410px;">
        <template #buttons>
          <el-button type="success" size="small" :icon="useRenderIcon(AddFill)" @click="addCross">
            区域设置
          </el-button>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <pure-table ref="tableRef" adaptive :default-expand-all="true" align-whole="center" size="small"  border showOverflowTooltip table-layout="auto"
            :loading="loading" :data="dataList" :columns="dynamicColumns" :pagination="pagination"
            :paginationSmall="true" :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
            <template #expand="{ row }">
              <ul class="table_expand">
                <li class="station">
                  <div class="title">
                    <span>通行车辆：</span>
                  </div>
                  <div>
                    <el-tag size="small" type="success" v-for="v in row.agvNameList" :key="v" style="margin:5px 5px;">
                      {{v}}
                    </el-tag>
                  </div>
                </li>
              </ul>
            </template>
            <template #operation="{ row }"> 
              <el-button class="reset-margin" link type="primary" size="small"
                @click="crossUp(row.id)">
                编辑
              </el-button>
              <el-button class="reset-margin" link type="danger" size="small" style="margin-left: 0px;"
                @click="deleteCross(row)">
                删除
              </el-button>
            </template>
          </pure-table>
        </template>
      </PureTableBar>

      <!-- 设置任务区域地图 -->
      <div class="mapDraw mt-2">
        <div class="mapCross">
          <div class="mapCorrd">
            <p>x:{{mouseCorrd.x}},y:{{mouseCorrd.y}}</p>
          </div>
          <div id="canvasMap" ref="map"></div>
        </div>
      </div>
    </div>

    <!-- 抽屉 -->
    <el-drawer
        v-model="pureMap.crossSwitch"
        :title="isUpdate ? '修改任务区域' : '新增任务区域'"
        direction="ltr"
        size="400px"
        :close-on-click-modal="true"
        :modal="false"
        modal-class="modalCross"
      >
        <el-alert title="可以通过双击右侧地图来添加任务区域坐标" type="warning" center :closable="false" style="margin-bottom:20px" />
        <!-- <crossForm :formInline="formInline" :isUpdate="isUpdate" ></crossForm> -->
        <crossForm :isUpdate="isUpdate" ref="crossRef" ></crossForm>
    </el-drawer>

  </div>
</template>

<script lang='ts' setup>
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDept } from "./utils/hook";
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { getCross } from '@/utils/api/dispatch/cross'
import mapCross from "./components/mapCross.vue";
import { initKonvaStage, mouseCorrd } from '@/views/home/components/dxfMap'
import { readFile } from '@/views/home/components/readFile'
import { useMapStoreHook } from "@/store/modules/map";
import crossForm from './crossForm.vue'
import { websock } from '@/utils/webScoket'
import { ElMessageBox } from 'element-plus'
import { message } from "@/utils/message";
import { Van, Guide, ArrowUp, ArrowDown } from '@element-plus/icons-vue' 
import { taskareaList, taskareaAdd, taskareaUpdate, taskareaDel, getTaskarea } from '@/utils/api/dispatch/jobRegion'

// iconify-icons
import AddFill from "@iconify-icons/ri/add-circle-line";
import EditPen from "@iconify-icons/ep/edit-pen";
import outlineDelete from '@iconify-icons/ic/outline-delete';
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";

const formRef = ref();
const map = ref()
const pureMap = useMapStoreHook()
var isUpdate = ref(false)
const crossRef = ref(null)
var isContract = ref(false)
var crossList:any = ref([])

// 监听抽屉开关，当抽屉关闭时刷新列表数据
watch(() => pureMap.crossSwitch, (newValue) => {
  if(!newValue) {
    const color = 'rgba(52, 120, 198, 1)'
    pureMap.targetCross.children.forEach(v=>{
      if(v.name() === 'circle'){
        v.fill(color)
      }else{
        v.stroke(color)
      }
    })
    onSearch()
  }
})

// 车辆移除任务区域
function agvClose(row,agvid){
  ElMessageBox.confirm(
    `是否确认将${agvid}移出${row.name}任务区域?`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消' ,
      type: 'warning',
      center: true
    }
  ).then(() => {
    websock.send(JSON.stringify({ type:'移出任务区域', data:row.id, agvid }));
    message(`提交成功`, { type: "success" });
  }).catch(() => { })
}

// 任务区域新增
function addCross(){
  pureMap.operateDrawer(true)
  isUpdate.value = false
  crossRef.value?.resetForm(crossRef.value.getRef())
}

// 任务区域编辑
function crossUp(id: number){
  pureMap.$patch({
    crossSwitch: true
  })
  
  nextTick(()=>{
    crossRef.value.crossUpdate(id)
  })
}

// 删除任务区域
function deleteCross(row){
  ElMessageBox.confirm(
    `是否确认删除名称为${row.name}的数据项?`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    }
  ).then(() => {
    taskareaDel(row.id).then(res => {
      if (res.Code === 0) {
        pureMap.stageKonva.find(`.job-${row.name}`)[0].destroy()
        message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
        onSearch();
      }
    })
  }).catch(() => { })
}

onMounted(()=>{
  readFile().then(data => {
    initKonvaStage('canvasMap', map, data, false)
  })
})

onUnmounted(()=>{
  pureMap.clearCross()
})

const {
  columns,
  loading,
  dataList,
  handleDelete,
  form,
  onSearch,
  resetForm,
  pagination,
  handleSizeChange,
  handleCurrentChange,
  agvCrossSwitch,
  crossSearch,
  expandOpen
} = useDept();

</script>

<style lang="scss" scoped>
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
.table_expand{
  padding-left: 15px;
}
.center_bg{
  display: flex;
  justify-content: space-between;
  height: 100%;
}
.mapDraw{
  width: calc(100% - 420px);
  background: white;
  .mapCross{
    position: relative;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, rgba(62, 61, 61,0.4) 2%, transparent 0%) 0 0, linear-gradient(180deg, transparent 99%,rgba(62, 61, 61,0.4) 1%) 0 0;
    background-size: 50px 50px;
    background-color: #001529;
  }
  #canvasMap{
    width: 100%;
    height: 100%;
  }
}

.lookAgv{
  height: 23px;
  margin-left: 15px;
  vertical-align: bottom;
  &:hover{
    cursor: pointer;
  }
}
.station{
  display: flex;
  align-items: center;
  .title{
  }
  .el-icon:hover{
    cursor: pointer;
  }
  .stationArr{
    width: 380px;
    height: 30px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

</style>